package com.plx.Controll;

import com.plx.pojo.Result;
import com.plx.pojo.employees;
import com.plx.service.employeesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.concurrent.TimeUnit;

@CrossOrigin
@RestController
@RequestMapping("/List")//通用请求路径
public class employeesController {
    @Autowired
    private employeesService employeesService;
    //注入
    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping
    public Result findAll() {
        String key = "employeesList";
        //1.查询缓存，获取缓存的部门数据列表
        List<employees> employeesList = (List<employees>) redisTemplate.opsForValue().get(key);
        // 2.判断缓存中获取的数据是否有效
        if (employeesList == null) {
            //2.1无效，从mysql数据库中获取数据，并且写入换缓存
            employeesList = employeesService.findAll();
            redisTemplate.opsForValue().set(key, employeesList);
            //加入定时器，定期刷新缓存，更新数据库
//            redisTemplate.opsForValue().set(key, employeesList, 1, TimeUnit.MINUTES);
        }
            //2.2有效，直接返回
        return Result.success(employeesList);
    }

    @DeleteMapping
    public Result deleteById(String id) {
        employeesService.deleteById(id);
        return Result.success();
    }

    @PostMapping
    public Result add(@RequestBody employees employees) {
        //调用业务
        employeesService.addEmp(employees);
        //返回结果值
        return Result.success();
    }

    ///{id}路径传递占位符
    //方法参数名字要与路径占位符参数名一致
    @GetMapping("/{id}")
    public Result selectById(@PathVariable String id) {
        //调用业务层。通过ID查询员工
       employees EMP= employeesService.EMPById(id);
       //返回结果
       return Result.success(EMP);

        }
    @PutMapping
    public Result Cupdate(@RequestBody employees eeemp) {
        employeesService.Supdata(eeemp);
        return Result.success();
    }
    }


